const express = require("express");
const router = express.Router();
const Blog = require("../model/blog");
const User = require("../model/user");
const Common = require("../model/common");

// 所有帖子
router.get("/allpost", (req, res) => {
  allpost = {
    status: 0,
    data: {
      post: [],
    },
  };
  Blog.find().then(async (data) => {
    // console.log(data)
    // 外层循环 所有用户
    for (let index = 0; index < data.length; index++) {
      var blogDetail = {};
      // for(let i = 0 ; i < data[index].blog.length ; i++){
      //   console.log(data[index].blog[i])
      //   var blogData = data[index].blog[i]
      // }

      await User.findOne({ _id: data[index].uid }).then(async function (
        Userdata
      ) {
        blogDetail.id = Userdata._id;
        blogDetail.name = Userdata.username;
        blogDetail.avatar_url = Userdata.avatar_url || "";
        var blogList = [];

        // 判断blog是否是被标记为删除的  使用find方法只有在条件满足才返回
        // 每个用户会有多个帖子
        for (let i = 0; i < data[index].blog.length; i++) {
          // console.log(data[index].blog[i])
          var blog = data[index].blog[i];
          if (!blog.isDelete) {
            var commonDate = [];
            // 每个帖子有多个评论
            await Common.findOne({ blogId: blog._id }).then(function (
              CommonData
            ) {
              // console.log(CommonData)
              if (CommonData !== null) {
                for (let i = 0; i < CommonData.common.length; i++) {
                  var common = CommonData.common[i];
                  if (!common.isDelete) {
                    commonDate.push({
                      _id: common._id,
                      uid: common.uid,
                      realname: common.realname,
                      avatar_url: common.avatar_url,
                      content: common.content,
                      time: common.time,
                    });
                  }
                }
              }
            });
            blogList.push({
              _id: blog._id,
              title: blog.title,
              content: blog.content,
              img: blog.img,
              time: blog.time,
              comment: commonDate,
            });
            // console.log("blogList",blogList)
          }
        }
        // console.log("blogList",blogList)
        blogDetail.blogList = blogList;
      });
      // console.log(blogDetail)

      allpost.data.post.push(blogDetail);
    }
    res.json({ allpost }, 201);
  });
});

// 帖子详情
router.post("/Postdetails1", async (req, res) => {
  var reqData = {};
  var flat = true;
  var uid = req.body.uid;
  var blogId = req.body.blogId;
  await Blog.findOne({ uid: uid }).then((data) => {
    for (let i = 0; i < data.blog.length; i++) {
      if (data.blog[i]._id == blogId && !data.blog[i].isDelete) {
        // console.log(data.blog[i])
        reqData = {
          msg: "查询成功",
          status: 0,
          uid: uid,
          blogId: blogId,
          title: data.blog[i].title,
          content: data.blog[i].content,
          img: data.blog[i].img,
          time: data.blog[i].time,
        };
        flat = false;
        return;
      } else if (data.blog[i]._id == blogId && data.blog[i].isDelete) {
        reqData = {
          msg: "查询失败,该帖子已经被删除",
          status: 1,
        };
        flat = false;
        return;
      }
    }
    if (flat) {
      reqData = {
        msg: "查询失败",
        status: 1,
      };
    }
  });
  res.json(reqData, 201);
  // Blog
});

// 获取当前用户发布过的帖子
router.get("/Retrieve", async (req, res) => {
  var uid = req.query.uid;
  var isHad = true;
  var reqData = {
    msg: "查询成功",
    status: 0,
    uid: uid,
    blogList: [],
  };
  try {
    await User.findOne({ _id: uid }).then((data) => {
      if (data === null) {
        reqData = {
          msg: "查询失败,用户不存在",
          status: 0,
        };
        isHad = false;
      }
    });
  } catch (e) {
    reqData = {
      msg: "查询失败,用户不存在,id格式不正确",
      status: 0,
    };
    isHad = false;
  }
  if (isHad) {
    await Blog.findOne({ uid: uid }).then((data) => {
      for (let i = 0; i < data.blog.length; i++) {
        if (!data.blog[i].isDelete) {
          reqData.blogList.push({
            blogId: data.blog[i]._id,
            title: data.blog[i].title,
            content: data.blog[i].content,
            img: data.blog[i].img,
            time: data.blog[i].time,
          });
        }
      }
    });
  }
  res.json(reqData, 201);
  // Blog
  // Blog
});

// 创建帖子
router.post("/creatBlog", async (req, res) => {
  var uid = req.body.uid;
  var title = req.body.title;
  var content = req.body.content;
  var img = JSON.stringify(req.body.img);
  var reqData = {};
  var isHad = true;
  // console.log('uid,title,content:',uid,title,content)
  try {
    await User.findOne({ _id: uid }).then((data) => {
      if (data === null) {
        reqData = {
          msg: "创建失败,用户不存在",
          status: 0,
        };
        isHad = false;
      }
    });
  } catch (e) {
    reqData = {
      msg: "创建失败,用户不存在,id格式不正确",
      status: 0,
    };
    isHad = false;
  }
  if (isHad) {
    await Blog.findOne({ uid: uid }).then(function (data) {
      // console.log(data)
      // 如果这个用户没写过就创建一个新的
      if (data === null) {
        // console.log(data._id);
        var blog = new Blog({
          uid: uid,
          blog: {
            title: title,
            content: content,
            img: img,
            time: Date.now(),
          },
        });
        return blog.save();
      }
      // 否则就直接在数组中添加
      else {
        var arr = data.blog;
        arr.push({
          title: title,
          content: content,
          img: img,
          time: Date.now(),
        });
        Blog.findOneAndUpdate({ uid: uid }, { blog: arr }, { new: true }).then(
          (data) => {
            console.log(data);
          }
        );
      }
      // res.json({data:'Postdetails1'},201);
    });
    reqData = {
      msg: "创建成功",
      status: 0,
    };
  }
  // blog(req.request.body).save()
  res.json(reqData, 201);
});

// 获取评论
router.post("/getCommont", async (req, res) => {
  var reqData = {
    CommentList: [],
  };
  var blogId = req.body.blogId;
  try {
    await Common.findOne({ blogId: blogId }).then((data) => {
      if (data === null) {
        reqData = {
          msg: "查询失败,该blog不存在或者没有评论",
          status: 0,
        };
      } else {
        for (let i = 0; i < data.common.length; i++) {
          if (!data.common[i].isDelete) {
            reqData.CommentList.push({
              uid: data.common[i].uid,
              realname: data.common[i].realname,
              avatar_url: data.common[i].avatar_url,
              content: data.common[i].content,
              time: data.common[i].time,
            });
          }
        }
        reqData.msg = "查询成功";
        reqData.status = 1;
      }
    });
  } catch (e) {
    reqData = {
      msg: "查询失败,该blog不存在或者没有评论,id格式不正确",
      status: 0,
    };
  }
  res.json(reqData, 201);
});

// 创建评论
router.post("/creatComment", async (req, res) => {
  let isBlogDelete = false;
  var reqData = {};
  var uid = req.body.uid;
  var blogUserId = req.body.blogUserId; // 帖子发布者id
  var blogId = req.body.blogId;
  var realname = req.body.realname;
  var avatar_url = req.body.avatar_url;
  var content = req.body.content;
  await Blog.findOne({ uid: blogUserId }).then(function (data) {
    data.blog.map((blogData) => {
      if (blogData._id == blogId) {
        // console.log(blogData)
        isBlogDelete = blogData.isDelete;
      }
    });
  });
  if (!isBlogDelete) {
    Common.findOne({ blogId: blogId }).then(function (data) {
      if (data === null) {
        var Comment = new Common({
          blogId: blogId,
          common: {
            uid: uid,
            realname: realname,
            avatar_url: avatar_url,
            content: content,
            time: Date.now(),
          },
        });
        return Comment.save();
      } else {
        var arr = data.common;
        arr.push({
          uid: uid,
          realname: realname,
          avatar_url: avatar_url,
          content: content,
          time: Date.now(),
        });
        Common.findOneAndUpdate(
          { blogId: blogId },
          { common: arr },
          { new: true }
        ).then((data1) => {
          // console.log(data1)
        });
      }
    });
    reqData = {
      msg: "评论成功",
      status: 0,
    };
  } else {
    reqData = {
      msg: "评论的文章已经被删了",
      status: 1,
    };
  }
  res.json(reqData, 201);
});

// 修改帖子
router.post("/updateBlog", async (req, res) => {
  var reqData = {};
  var uid = req.body.uid;
  var blogId = req.body.blogId;
  var title = req.body.title;
  var content = req.body.content;
  var img = JSON.stringify(req.body.img);
  var isHad = true;
  try {
    await User.findOne({ _id: uid }).then((data) => {
      if (data === null) {
        reqData = {
          msg: "修改失败,用户不存在",
          status: 0,
        };
        isHad = false;
      }
    });
  } catch (e) {
    reqData = {
      msg: "修改失败,用户不存在,id格式不正确",
      status: 0,
    };
    isHad = false;
  }
  if (isHad) {
    await Blog.findOne({ uid: uid }).then(async function (data) {
      for (let i = 0; i < data.blog.length; i++) {
        if (data.blog[i]._id == blogId && !data.blog[i].isDelete) {
          data.blog[i] = {
            _id: data.blog[i]._id,
            title: title,
            content: content,
            img: img,
            time: data.blog[i].time,
          };
          reqData = {
            msg: "修改成功",
            status: 1,
          };
          // console.log(data.blog[i])
        } else if (data.blog[i]._id == blogId && data.blog[i].isDelete) {
          reqData = {
            msg: "修改失败,帖子已经被删了",
            status: 0,
          };
        }
      }
      await Blog.findOneAndUpdate({ uid: uid }, { blog: data.blog });
    });
  }
  res.json(reqData, 201);
});
// 删除 删除时要注意 用户 文章 评论之间的关系  比如文章标记为删除该文章下的评论也得标记为删除
// 删除帖子
router.delete("/deleteBlog", async (req, res) => {
  var blogId = req.query.blogId || false;
  var uid = req.query.uid || false;
  if (blogId && uid) {
    var deleteData = {};
    await Blog.findOne({ uid: uid }).then(async function (data) {
      var blog = data.blog.map((blogData) => {
        if (blogData._id == blogId) {
          blogData.isDelete = true;
        }
        return blogData;
      });
      deleteData = blog;
      await Blog.findOneAndUpdate({ uid: uid }, { blog: blog });
    });
    // 将该文章下的评论也改为false
    await Common.findOne({ blogId: blogId }).then(async function (data) {
      var common = data.common.map((commonData) => {
        commonData.isDelete = true;
        return commonData;
      });
      await Common.findOneAndUpdate({ blogId: blogId }, { common: common });
    });

    res.json(
      {
        msg: "删除成功",
        status: 0,
      },
      201
    );
  } else {
    res.json(
      {
        msg: "删除失败",
        status: 1,
      },
      201
    );
  }

  // Blog
});
module.exports = router;
